<?php
	$subdirname = $argv[1];
	$movtypes	= array("mov","avi","mpg","mpeg","divx","ogm","mp4","mkv","m4v","mp4v");	// What are movie file extensions
	$subdir = opendir($subdirname);

		$xml		= array();
		$xmlfile	= false;
		$cover		= false;
		$subtitles	= false;
		$listavi	= array();
		$listavism	= array();
		$sample		= "";
		$trailer	= "";
		$movcount	= 0;
		$xmlcount	= 0;
		$jpgcount	= 0;
		$srtcount	= 0;
		$nfofile	= "";


	$temp = array();
	exec("defaults read com.tegosaurus.appletvdatamaker",$temp);
	array_shift($temp); array_pop($temp);
	$prefs = array();
	foreach($temp as $line){
		$line = substr($line,0,strlen($line)-1);
		list($key,$value) = explode(" = ",trim($line),2);
		$prefs[$key] = $value;
	}
	if(!isset($prefs["posterIMP"])){ $prefs["posterIMP"] = 1; }
	if(!isset($prefs["posterDVD"])){ $prefs["posterDVD"] = 1; }
	if(!isset($prefs["posterAMZ"])){ $prefs["posterAMZ"] = 1; }





		while(false !== ($file = readdir($subdir))){
			if(substr($file,0,1) == "."){ continue; }				// No hidden files / dirs
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if($ext == ""){ continue; }
			if(in_array($ext, $movtypes)){							// It is a movie
				$movcount++;
				if(strpos($file, "samp") > 0){						// It is a sample
					$sample = $file;
				}elseif(strpos($file, "trailer") > 0){				// It is a trailer
					$trailer = $file;
				}else{												// It is a part of the movie
					array_push($listavism, substr($file, 0, strrpos($file, ".")));
					array_push($listavi, $file);
					if($filesize == 0){								// Get file size of first movie, for subtitle downloading...
						$filesize = filesize($subdirname."/".$file);
					}
				}
			}elseif($ext == "xml"){
				$xmlfile = $file;
			}
		}
		
		if($argv[2] == "cover.jpg"){
			; // Cover is there already... just copy it
		}else{
			$temp = explode("/",$subdirname);
			$movie = $temp[count($temp)-2];
			$movTitle   = preg_replace("/\s*?\(.*/","",$movie);		// Remove everything after first bracket (year, rip type, ...)
			
			if(file_exists($subdirname."movietitle.txt")){
				$movTitle = file_get_contents($subdirname."movietitle.txt");
			}
			
			$posterdone = false;
			if($prefs["posterIMP"]){
				// Find out year
				if(file_exists($subdirname.$xmlfile)){
					$xmldata = file_get_contents($subdirname.$xmlfile);
					$year = preg_replace("/.+?\<published\>/s","",$xmldata);
					$year = substr($year,0,4);
				}
				
				// Get year's list - from cache or new (cache refresh once a week)
				if(file_exists("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imp/".$year.".tab")){
					$stat = stat("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imp/".$year.".tab");
					if($stat["mtime"] > time() - 24*7*3600){
						$file = file("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imp/".$year.".tab");
						$movieposters = array();
						foreach($file as $line){
							$temp = explode("\t",$line);
							$movieposters[$temp[0]] = explode(",",$temp[1]);
						}
					}
				}
				if(!isset($movieposters[strtolower($movTitle)])){
					$posfile = fopen("/Users/".$_ENV["USER"]."/Library/Caches/com.tegosaurus.appletvdatamaker/imp/".$year.".tab","w");
					$parts = preg_split("/\<tr width \= 200 bgcolor \= \#\d\d\d\d\d\d\>/",implode("",file("http://www.impawards.com/2007/standard.html")));
					array_shift($parts);
	
					$movieposters = array();
					foreach($parts as $movie){
						$lines = explode("\n",$movie);
						$movietitle = trim(str_replace("<td><font size=+1>","",str_replace("</font></td>","",$lines[1])));
						$posters = array();
						preg_match_all("/<A HREF = \"(.+?)\"/",$lines[2],$posters);
						fwrite($posfile,$movietitle."\t".implode(",",$posters[1])."\n");
						$movieposters[strtolower($movietitle)] = $posters[1];
					}
				}

				if(isset($movieposters[strtolower($movTitle)])){
					// Get poster URL
					$file = implode("",file("http://www.impawards.com/2007/".array_shift($movieposters[strtolower($movTitle)])));


					$temp = array();
					preg_match("/<img SRC=\"(.+?)\" ALT = \"Movie Poster Image for /",$file,$temp);
					$poster = "http://www.impawards.com/2007/".$temp[1];
					// Download poster
					$cover = file_get_contents($poster);
					$jpg = fopen($subdirname."cover.jpg","w");
					fwrite($jpg, $cover);
					fclose($jpg);
					$posterdone = true;
				}
			}

			
			
			if(!$posterdone AND ($prefs["posterAMZ"] == 1)){
				$searchIndex	= 'DVD';
				$amazonAssoc	= 'mycongre-20';
				$amazonId		= '0P7K5S7GFNHH7ZPJB1R2';
				$query			= urlencode($movtitle);
				$url			= "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&IdType=ASIN&ResponseGroup=Large&SearchIndex=" .  $searchIndex . "&Operation=ItemSearch&Keywords=" . $query . "&AWSAccessKeyId=" . $amazonId . "&AssociateTag=" . $amazonAssoc . "&Version=2007-05-14";
				
				$ch 	= 	curl_init();
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_URL, $url);
				$data 	= 	curl_exec($ch);
				curl_close($ch);
				
				$xml	= simplexml_load_string($data);
				$mark	= $xml->TotalPages;
				$error	= $xml->ErrorMsg;
				
				$lowscore = 100000;
				
				if($xml->Items->Item){
					$x = 0; // set counter to handle result amounts
					foreach ($xml->Items->Item as $item){
						if ($x < 5){
							$result = $item->ItemAttributes->Title;
							if(round(10000 * levenshtein(strtolower($movtitle), strtolower($result))/strlen($movtitle) / similar_text(strtolower($movtitle), strtolower($result))/strlen($movtitle),2) < $lowscore){
								$lowscore = round(10000 * levenshtein(strtolower($movtitle), strtolower($result))/strlen($movtitle) / similar_text(strtolower($movtitle), strtolower($result))/strlen($movtitle),2);
								$theResult = $item;
							}
						}
					}
				}
				unset($xml);
				
				if(isset($theResult)){
					$img = $theResult->LargeImage->URL;
					$imgurl = substr($img,0,strrpos($img,"/")+1).substr($img,strrpos($img,"/")+1,strpos($img,".",strrpos($img,"/")+1)-strrpos($img,"/")-1).".jpg";
					if($imgurl != ".jpg"){
						$cover = file_get_contents($imgurl);
						$jpg = fopen($subdirname."cover.jpg","w");
						fwrite($jpg, $cover);
						fclose($jpg);
						$posterdone = true;
					}
				}
			}
	
			
			
			
			
			
			
			
			if(!$posterdone AND ($prefs["posterDVD"] == 1)){
				$userID = rand(99000000000000,99999999999999);
				$searchURL = "http://www.dvdempire.com/Exec/v5_search_item.asp?userid=".$userID."&site_media_id=&site_id=4&pp=&used=0&search_refined=0&string=";
				$searchpage = file_get_contents($searchURL.urlencode($movTitle));
	
				$itemstartpos = strpos($searchpage, 'item_id=');
				if($itemstartpos){
					$itemendpos = strpos($searchpage, '&', $itemstartpos-1);
					$itempart   = substr($searchpage, $itemstartpos + 8, $itemendpos - $itemstartpos - 8);
					if($itempart != ""){
						$imgurl = "http://images2.dvdempire.com/gen/movies/".$itempart."h.jpg";
						$cover = file_get_contents($imgurl);
						$jpg = fopen($subdirname."cover.jpg","w");
						fwrite($jpg, $cover);
						fclose($jpg);
					}
				}
			}
		}
		
	// Wegschrijven...
	
	sort($listavi);
	$i = 0;
	foreach($listavi as $avi){
		$ext = strtolower(substr($avi, strrpos($avi, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$avi));
	}
	if($sample != ""){
		$ext = strtolower(substr($sample, strrpos($sample, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$sample));
	}
	if($trailer != ""){
		$ext = strtolower(substr($trailer, strrpos($trailer, ".")+1));
		copy($subdirname."cover.jpg", $subdirname.str_replace(".".$ext,".jpg",$trailer));
	}
	echo '1';
?>